package com.xufx.algorithm.doublepointer;

/**
 * leetcode 11. Container with most water
 * @link https://leetcode.cn/problems/container-with-most-water/description/
 * describe: You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).
 * Find two lines that together with the x-axis form a container, such that the container contains the most water.
 * Return the maximum amount of water a container can store.
 *
 * Notice that you may not slant the container.v
 * 
 * example:
 *  Input: height = [1,8,6,2,5,4,8,3,7]
 *  Output: 49
 *  Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.
 *
 *
 * NOTICE: 雨水问题，很大可能就是用双指针。可以通过模式识别，题目要求'''左右移动'''两边
 */
public class Leetcode11ContainerWithMostWater {

    public static void main(String[] args) {
        int[] height = new int[]{1,8,6,2,5,4,8,3,7};
        int result = maxArea(height);
        System.out.println(result);
    }

    private static int maxArea(int[] height) {
        // 左右移动 --> 想起双指针
        // 先处理一下特殊情况
        int len = height.length;
        if(len == 2){
            return Math.min(height[1], height[0]);
        }
        // 定义双指针
        int left  = 0;
        int right = len - 1;
        int res   = 0;

        while(left < right){
            res = Math.max(res, (right - left) * Math.min(height[left], height[right]));
            if(height[left] > height[right]){
                right --;
            }else{
                left ++;
            }
        }
        return res;
    }
}
